<?php 

/*
// Usage example: 
  
  // Do this stuff in your config file 
  include_once('cache-kit.php'); 
  $cache_active = true;  
  $cache_folder = 'cache/';   
  
  // Now you can convert any time-consuming but rarely-changing data module into  
  // a fast cached module. This example rebuilds the calendar only every 5 minutes.  
  function helloWorld(){ 
   $result = acmeCache::fetch('helloWorld', 10); // 10 seconds 
   if(!$result){ 
    $result = '<h2> Hello world</h2> <p>Build time: '.date("F j, Y, g:i a").'</p>'; 
    acmeCache::save('helloWorld', $result); 
   } else echo('Cached result<br/>');  
   return $result; 
  } 

  // now use the content module function just like you normally would -- caching is automatic! 
  echo(helloWorld()); 

*/

class acmeCache{  

 // public functionality, acmeCache::fetch() and acmeCache::save() 
 // ========================= 

 function fetch($name, $refreshSeconds = 0){ 
  if(!$refreshSeconds) $refreshSeconds = 60;  
  $cacheFile = acmeCache::cachePath($name);  
  if(file_exists($cacheFile) and 
   ((time()-filemtime($cacheFile))< $refreshSeconds))  
   $cacheContent = file_get_contents($cacheFile); 
  return $cacheContent; 
 }  
  
 function save($name, $cacheContent){ 
  
 	$cacheFile = acmeCache::cachePath($name); 
	acmeCache::savetofile($cacheFile, $cacheContent); 
 }  

 // for internal use  
 // ==================== 
 function cachePath($name){ 
  global $admin_area;
  if ($admin_area=="1")
  	$cacheFolder = "config/cache/";
  else
  	$cacheFolder = "admin/config/cache/";
  	
  if(!$cacheFolder) $cacheFolder = trim($_SERVER['DOCUMENT_ROOT'],'/').'/cache/'; 
  return $cacheFolder . $name . '.cache'; 
 } 
  
 function savetofile($filename, $data){ 
  $dir = trim(dirname($filename),'/').'/';  
  acmeCache::forceDirectory($dir);   
  $file = fopen($filename, 'w'); 
  fwrite($file, $data); fclose($file); 
 }  
   
 function forceDirectory($dir){ // force directory structure  
  return is_dir($dir) or (acmeCache::forceDirectory(dirname($dir)) and mkdir($dir, 0777)); 
 } 

} 
?>